package cn.afactory.tygz.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.model.SnsSubjectDetailList;
import cn.afactory.tygz.model.SnsTopicInfo;
import cn.afactory.tygz.model.SnsTopicInfoList;
import cn.afactory.tygz.ui.activities.TopicDetailActivity;
import cn.afactory.tygz.ui.adapter.TopicHotListAdapter;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

/**
 * Created by Kenneth on 15/9/17.
 */
public class TopicHotListFragment extends cn.afactory.tygz.ui.base.BaseFragment implements TopicHotListAdapter.OnFollowClickListener{

    private static final String TAG = TopicHotListFragment.class.getSimpleName();
    protected SnsControler mController;
    protected TopicHotListAdapter mAdapter;
    private List<SnsTopicInfo> mList = new ArrayList<SnsTopicInfo>();

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_GET_TOPIC_LIST_OK:
                if (msg.obj instanceof SnsTopicInfoList) {
                    hideErrorPage(-1);
                    SnsTopicInfoList t = (SnsTopicInfoList) msg.obj;
                    if (t.value != null && t.value.size() >= 0) {
                        try {
                            if (msg.arg1 == SnsControler.MSG_DATA_FROM_CACHE && mAdapter.getCount() == 0 && mLastReqTime == 0) {
                                mList.addAll(t.value);
                            } else {
                                if (mLastReqTime == 0) {
                                    mList.clear();
                                }
                                mList.addAll(t.value);
//                                mLastReqTime = t.value.get(t.value.size() - 1).addTime;
                                mLastReqTime = System.currentTimeMillis();
                            }

                            mAdapter.setData(mList);
                            mPageIndex = (mList.size() / mPageSize) + 1;

                            if (plistview.isRefreshing()) {
                                plistview.onRefreshComplete();
                            }
                            if (t.value.size() < mPageSize) {
                                plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                plistview.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (mAdapter.getCount() == 0) {
                            showNullPage(true);
                        }
                    }
                }
                break;
            case SnsControler.MSG_GET_TOPIC_LIST_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadDatas();
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, "获取附近的动态失败！");
                }
                break;
            default:
                break;
        }

        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addTitleBar = false;
        mController = new SnsControler(mContext, mUIHandler, null);
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fg_restaurant_list, null);
        initViews(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    /**
     * 初始化组件 views
     *
     * @param view
     */
    private void initViews(View view) {
        plistview = (PullToRefreshListView) view.findViewById(R.id.plv_subject);
        mAdapter = new TopicHotListAdapter(mContext,mList);
        mAdapter.setOnFollowClickListener(this);
        plistview.setAdapter(mAdapter);
        plistview.setMode(PullToRefreshBase.Mode.BOTH);
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadSubjectData(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadSubjectData(false);
            }
        });
        plistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView lv = plistview.getRefreshableView();
                if (position >= lv.getHeaderViewsCount()) {
                    position -= lv.getHeaderViewsCount();
                }
                Intent intent = new Intent(mContext, TopicDetailActivity.class);
                SnsTopicInfo snsTopicInfo = (SnsTopicInfo) mAdapter.getItem(position);
                intent.putExtra(TopicDetailActivity.EXT_DATA_TAG, snsTopicInfo);
                startActivity(intent);
            }
        });
    }


    private void initData(){
        startLoadDatas();
    }

    private void startLoadDatas(){
        startLoadSubjectData(true);
    }

    /**
     * 加载listview数据
     */
    private int mPageIndex = 1;
    private int mPageSize = 10;
    private long mLastReqTime = System.currentTimeMillis();
    protected void startLoadSubjectData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mLastReqTime = 0;
            mList.clear();
        }
        mController.doGetTopicList(2, 1, mPageIndex, mPageSize);
    }

    @Override
    public void onClickFollowButton(TextView follow, SnsTopicInfo snsTopicInfo) {
        if (snsTopicInfo.isAttentioned) {
            mController.doUnFollowTopic(follow, snsTopicInfo);
        } else {
            mController.doFollowTopic(follow, snsTopicInfo);
        }
    }

    @Override
    public void onClickSubjectList(String str) {

    }
}

